package pl.cba.solgar.game.rogal;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

import org.newdawn.slick.Color;

import pl.cba.solgar.game.rogal.console.Console;

public class MessageConsole {
	private static MessageConsole instance;
	private LinkedList<Message> messages;
	final private int posx;
	final private int posy;

	final private int width;
	final private int height;

	public static MessageConsole createInstance(int posx, int posy, int width, int height) {
		if (instance == null)
			instance = new MessageConsole(posx, posy, width, height);
		return instance;
	}

	public static MessageConsole getInstance() {
		return instance;
	}

	private MessageConsole(int posx, int posy, int width, int height) {
		this.posx = posx;
		this.posy = posy;
		this.width = width;
		this.height = height;
		messages = new LinkedList<Message>();
	}

	public Iterator<Message> getIterator() {
		return messages.iterator();
	}

	public void postMessage(String msg) {
		if (!messages.isEmpty() && messages.getFirst().msg.compareTo(msg) == 0) {
			messages.getFirst().times += 1;
		}
		else {
			Message message = new Message();
			message.msg = msg;
			message.times = 1;
			messages.addFirst(message);
		}
	}

	public int lines() {
		return messages.size();
	}

	public void render(Console c) {
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				c.setChar(' ', x, y, Color.black, null);
			}
		}
		try {
			Iterator<Message> iterator = messages.iterator();
			Message msg = iterator.next();
			String msgText = msg.msg + (msg.times > 1 ? (" [x"+msg.times+"]") : "");
			c.setColor(Color.white);
			c.print(msgText, posx, posy);

			msg = iterator.next();
			msgText = msg.msg + (msg.times > 1 ? (" [x"+msg.times+"]") : "");
			c.setColor(Color.gray);
			c.print(msgText, posx, posy + 1);

			msg = iterator.next();
			msgText = msg.msg + (msg.times > 1 ? (" [x"+msg.times+"]") : "");
			c.setColor(Color.darkGray);
			c.print(msgText, posx, posy + 2);
		}
		catch (NoSuchElementException ex) {
			// do nothing
		}
	}

	public class Message {
		public String msg;
		public int times;
	}


}
